<template>
  <div class="wz_table" ref="table">
    <!--表头-->
    <div class="wz_table__header">
      <div class="wz_table__header__item-1" :style="{width: colItemWidth*2 + 'px'}">日期</div>
      <div class="number__rows">
        <div class="header__row1">
          <div v-for="(item, index) in wzTableHead" :key="index+'-'+item.weekNumber"
               :style="{width: colItemWidth + 'px'}" class="wz_table__header__item">
            {{ item.weekNumber }}
          </div>
        </div>
        <div class="header__row2">
          <div v-for="(item, index) in wzTableHead" :key="index+'-'+item.dayNumber"
               :style="{width: colItemWidth + 'px'}" class="wz_table__header__item">
            {{ item.dayNumber }}
          </div>
        </div>
      </div>
    </div>
    <!--  表格体  -->
    <div v-if="!loading" class="wz_table_body">
      <!-- 行 -->
      <div v-for="row in tableData" :key="row.employeeId" class="wz_table_body_row">
        <!-- 单元格 -->
        <div class="wz_table_body_head_item" :style="{width: colItemWidth * 2 + 'px'}">
          {{ row.employeeName }}
        </div>
        <el-popover
            v-for="(item,index2) in row.colData" :key="index2"
            placement="right"
            width="400"
            trigger="click"
            @click="popClick(item)"
            v-model="item.popShow"
            :disabled="item.isLessCurrentDay"
        >
          <!-- 弹出 -->
          <div class="classes">
            <div class="title">班次列表</div>
            <div class="main">
              <div v-for="classItem in item.classesList" :key="classItem.id" @click="classItemClick(item.classesList, classItem)" class="class_item"
                   :class="classItem.isCheck ? 'class_item_active':''">{{ classItem.classesName }}
              </div>
            </div>
            <div class="footer">
              <el-button type="primary" size="mini" icon="el-icon-circle-close" @click="item.popShow = false"
                        style="margin-right: 20px">关闭
              </el-button>
              <el-button type="primary" size="mini" icon="el-icon-s-promotion" @click="save(item, row, index2)">保存
              </el-button>
            </div>
          </div>
          <!-- ----------- -->
          <template #reference>
            <div
                :class="item.isLessCurrentDay ? 'disable': ''"
                 class="wz_table_body_item"
                 :style="{width: colItemWidth + 'px'}"
                 @click.stop="()=>colItemClick(item,index2,row)"
            >
              {{ item.classesNames }}
            </div>
          </template>
        </el-popover>

      </div>
    </div>
    <div v-else class="wz_table__loading"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      wzTableHead: [],
      colItemWidth: ''
    };
  },
  props: ['selectDate', 'tableData', 'getTableHeadData', 'refreshData', 'storeId', 'loading'],
  created() {
    this.init();
  },
  watch: {
    selectDate(newVal, oldVal) {
      let year = newVal.getFullYear();
      let month = newVal.getMonth();
      this.wzTableHead = this.getMonthDays(year, month);
      this.emitTableHeadData();
    }
  },
  mounted() {
    this.calculateWidth();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    init() {
      let year = this.selectDate.getFullYear();
      let month = this.selectDate.getMonth();
      this.wzTableHead = this.getMonthDays(year, month);
      this.emitTableHeadData();
    },
    emitTableHeadData() {
      this.$emit('getTableHeadData', this.wzTableHead);
    },
    classItemClick(classesList, item) {
      classesList.forEach(cla => {
        if (cla.id === item.id) {
          cla.isCheck = !cla.isCheck;
        }
      });
    },
    colItemClick(scheduleData, colIndex, rowData) {
      if (scheduleData.isLessCurrentDay) {
        return this.$message.warning('禁止对当日之前的排班操作！');
      }
      let params = {
        pageNum: 1,
        pageSize: 20,
        classesStatus: 'on',
        storeId: scheduleData.storeId
      };

      this.$http.post('common', `/web/classes/getByKeyword`, params).then(res => {
        res.data.records.forEach(item => {
          item.isCheck = false;
        });
        scheduleData.classesList = res.data.records;
        // 修改模式回显已选择班次
        scheduleData.classesList.forEach(clases => {
          if (scheduleData.classesIds.length > 0) {
            scheduleData.classesIds.forEach((id, index) => {
              if (id === clases.id) {
                clases.isCheck = true;
              }
            });
          }
        });
      });
    },
    // 打开弹窗
    popClick(item) {
      item.popShow = true;
    },
    // 保存
    save(item, row, index) {
      item.popShow = false;
      let year = this.selectDate.getFullYear();
      let month = this.selectDate.getMonth();
      let classesDate = String(year) + String(month + 1).padStart(2, '0') + String(this.wzTableHead[index].dayNumber).padStart(2, '0');
      let classesIds = [];
      item.classesList.forEach(cla => {
        if (cla.isCheck) {
          classesIds.push(cla.id);
        }
      });
      classesIds = classesIds.join(',');
      if (item.id !== '') { // 修改模式 or 删除模式
        if (classesIds.length < 1) { // 删除/common/web/scheduling/delete
          this.$http.delete('common', '/web/scheduling/delete', [item.id]).then(res => {
            if (res.success) {
              this.$message.success('保存成功！');
              this.$emit('refreshData', item.storeId);
            } else {
              this.$message(res.message);
            }
          });
        } else { //修改
          let params = {
            id: item.id,
            employeeId: row.employeeId,
            storeId: item.storeId,
            classesDate: classesDate,
            classesIds: classesIds
          };
          this.$http.put('common', '/web/scheduling/update', params).then(res => {
            if (res.success) {
              this.$message.success('保存成功！');
              this.$emit('refreshData', item.storeId);
            } else {
              this.$message(res.message);
            }
          });
        }
      } else { // 新增
        let params = {
          employeeId: row.employeeId,
          storeId: item.storeId,
          classesDate: classesDate,
          classesIds: classesIds
        };
        this.$http.post('common', '/web/scheduling/add', params).then(res => {
          if (res.success) {
            this.$message.success('保存成功！');
            this.$emit('refreshData', item.storeId);
          } else {
            this.$message(res.message);
          }
        });
      }
    },
    calculateWidth() {
      const element = this.$refs.table;
      if (element) {
        const width = element.offsetWidth; // 获取元素的布局宽度
        this.colItemWidth = element.offsetWidth / 34;
      }
    },
    handleResize() {
      this.calculateWidth();
    },
    getMonthDays(year, month) {
      // 获取该月份的第一天
      const firstDayOfMonth = new Date(year, month, 1);
      const firstDayOfMonthDay = firstDayOfMonth.getDay(); // 获取第一天是周几   星期天是0 星期一是1
      let arr = ['天', '一', '二', '三', '四', '五', '六'];
      let dayArray = [];
      let start = 1;
      let end = 7 - firstDayOfMonthDay + 1;
      let obj = {};
      let weekN = firstDayOfMonthDay;
      for (let i = start; i <= end; i++) {
        obj = {
          weekNumber: arr[weekN % 7],
          dayNumber: i
        };
        weekN++;
        dayArray.push(obj);
      }
      // 当月天数
      let totalDayNum = new Date(year, month, 0).getDate();
      while (end < totalDayNum - 7) {
        start = end + 1;
        end += 7;
        for (let i = start; i <= end; i++) {
          if (weekN > 7) {
            weekN = 1;
          }
          obj = {
            weekNumber: arr[weekN % 7],
            dayNumber: i
          };
          weekN++;
          dayArray.push(obj);
        }
      }
      if (end < totalDayNum) {
        for (let i = end + 1; i <= totalDayNum; i++) {
          if (weekN > 7) {
            weekN = 1;
          }
          obj = {
            weekNumber: arr[weekN % 7],
            dayNumber: i
          };
          weekN++;
          dayArray.push(obj);
        }
      }

      return dayArray;
    }
  }
};
</script>

<style scoped lang="scss">
.wz_table {
  .wz_table__header {
    display: flex;

    .wz_table__header__item, .wz_table__header__item-1 {
      padding: 10px;
      background-color: rgb(245, 247, 250);
      border: 1px solid rgb(235, 238, 245);
      text-align: center;
    }

    .wz_table__header__item-1 {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      font-weight: 400;
    }

    .number__rows {
      display: flex;
      flex-direction: column;

      .header__row1, .header__row2 {
        display: flex;
      }
    }
  }

  .wz_table_body {
    .disable {
      background-color: gray;
      color: white;
    }

    .wz_table_body_row {
      display: flex;
      height: 40px;

      .wz_table_body_item, .wz_table_body_head_item {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 10px;
        font-size: 12px;
        border: 1px solid rgb(235, 238, 245);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        cursor: pointer;
        height: 100%;
      }

      .wz_table_body_head_item {
        font-size: 16px;
      }

    }
  }

  .wz_table__loading {
    width: 30px;
    height: 30px;
    border: 2px solid rgb(3, 119, 237);
    border-top-color: transparent;
    border-radius: 100%;
    margin: 20px auto;
    animation: circle infinite 0.75s linear;

    // 转转转动画
    @keyframes circle {
      0% {
        transform: rotate(0);
      }
      100% {
        transform: rotate(360deg);
      }
    }

  }
}

.classes {
  .title {
    font-size: 20px;
    font-weight: 400;
    text-align: center;
    margin-bottom: 10px;
  }

  .main {
    display: flex;
    flex-wrap: wrap;

    .class_item {
      display: flex;
      justify-content: center;
      align-items: center;
      border: 1px solid #D9D9D9;
      color: #979797;
      font-size: 14px;
      padding: 10px;
      border-radius: 10%;
      margin-right: 10px;
      margin-bottom: 10px;
      cursor: pointer;
    }

    .class_item_active {
      border-color: #1E5AD3;
      color: #1E5AD3;
    }
  }

  .footer {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}


</style>
